<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <!-- alert提示条 -->
      <el-alert
        title="添加商品信息"
        type="info"
        :closable="false"
        show-icon
        center
      >
      </el-alert>
      <!-- 步骤条 -->
      <el-steps
        :active="activeIndex - 0"
        :space="200"
        finish-status="success"
        align-center
      >
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <el-form
        ref="addGoodFormRef"
        :rules="addGoodFormRules"
        :model="addGoodform"
        label-width="80px"
        label-position="top"
      >
        <!-- tabs标签页 -->
        <el-tabs
          tab-position="left"
          v-model="activeIndex"
          :before-leave="beforeLeave"
          @tab-click="tabsClick"
        >
          <!-- 基本信息 -->
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" id="formItem" prop="goods_name">
              <el-input v-model="addGoodform.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格（¥）" prop="goods_price">
              <el-input
                type="number"
                v-model="addGoodform.goods_price"
              ></el-input>
            </el-form-item>
            <el-form-item label="商品重量（KG）" prop="goods_weight">
              <el-input
                type="number"
                v-model="addGoodform.goods_weight"
              ></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input
                type="number"
                v-model="addGoodform.goods_number"
              ></el-input>
            </el-form-item>
            <el-form-item label="分类" prop="goods_cat">
              <el-cascader
                v-model="selectGoodsCate"
                :options="goodsCateList"
                :props="goodsCateProps"
                @change="goodsCataChange"
                clearable
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <!-- 商品参数 -->
          <el-tab-pane label="商品参数" name="1">
            <el-form-item
              v-for="item in goodsParamsMany"
              :key="item.attr_id"
              :label="item.attr_name"
            >
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox
                  :label="item1"
                  v-for="(item1, index) in item.attr_vals"
                  :key="index"
                  border
                  size="mini"
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <!-- 商品参数 -->
          <el-tab-pane label="商品参数" name="2">
            <el-form-item
              :label="item.attr_name"
              v-for="item in goodsParamsOnly"
              :key="item.attr_id"
            >
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <!-- 商品图片 -->
          <el-tab-pane label="商品图片" name="3">
            <el-upload
              class="upload-demo"
              :action="uploadURL"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture"
              :headers="uploadHeaders"
              :on-success="uploadSuccess"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <!-- 商品内容 -->
          <el-tab-pane label="商品内容" name="4">
            <quill-editor v-model="addGoodform.goods_introduce"></quill-editor>
          </el-tab-pane>
          <el-tab-pane label="完成" name="5">
            <el-alert type="success" :closable="false" center>
              <el-button type="success" @click="subAddGoods"
                >添加商品</el-button
              >
            </el-alert>
          </el-tab-pane>
          <el-tab-pane name="6">
            <el-alert
              title="添加商品完成"
              type="success"
              :closable="false"
              center
            >
            </el-alert>
            <div id="successBox">
              <div>
                恭喜你,添加完成!
              </div>
              <div>正在准备跳转到商品列表...</div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <!-- 预览图片对话框 -->
    <el-dialog title="上传图片" :visible.sync="reviewdialog" width="30%">
      <div><img :src="reviewPicPath" class="reviewPic" /></div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="reviewdialog = false">取 消</el-button>
        <el-button type="primary" @click="reviewdialog = false"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      //  步骤条选中状态
      activeIndex: '0',
      // 添加表单参数
      addGoodform: {
        goods_name: '',
        goods_cat: '',
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        goods_introduce: '',
        pics: [],
        attrs: []
      },
      // 添加表单验证规则
      addGoodFormRules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' },
          { min: 1, max: 5, message: '数量大于0且小于 99999', trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' },
          { min: 1, max: 5, message: '数量大于0且小于 99999', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' },
          { min: 1, max: 5, message: '数量大于0且小于 99999', trigger: 'blur' }
        ],
        goods_cat: [
          { required: true, message: '请输入商品分类', trigger: 'blur' }
        ]
      },
      // 商品分类数据
      goodsCateList: [],
      // 级联选择器选中的分类数据
      selectGoodsCate: [],
      // 级联选择器配置
      goodsCateProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      // 商品参数（动态）
      goodsParamsMany: {},
      // 商品参数（静态）
      goodsParamsOnly: {},
      // 图片上传路径
      uploadURL: 'http://127.0.0.1:8888/api/private/v1/upload',
      // 图片上传请求头
      uploadHeaders: { Authorization: window.sessionStorage.getItem('token') },
      // 控制预览图片对话框
      reviewdialog: false,
      // 预览图片路径
      reviewPicPath: '',
      // 判断是否完成添加
      addGoodsStatus: false,
      // 跳转到商品列表进度
      progress: 0
    }
  },
  created() {
    this.getGoodsCateList()
  },
  methods: {
    // 获取商品分类数据
    async getGoodsCateList() {
      const { data } = await this.$http.get('categories')
      if (data.meta.status !== 200) {
        return this.$message.error('商品列表获取失败')
      }
      this.$message.success('商品列表获取成功')
      console.log('商品列表获取成功')
      this.goodsCateList = data.data
      console.log(this.goodsCateList)
    },
    //  级联选择器发生分类改变
    goodsCataChange() {
      this.addGoodform.goods_cat = this.selectGoodsCate
      console.log(this.addGoodform.goods_cat)
    },
    // 在切换tags前触发
    beforeLeave(activeName, oldActiveName) {
      //  当未选中产品
      if (oldActiveName === '0' && this.selectGoodsCate.length !== 3) {
        this.$message.error('请将信息填写完整')
        return false
      }
      // 切换标签页时只能单层切换
      if (
        activeName - oldActiveName !== 1 &&
        activeName - oldActiveName !== -1
      ) {
        return false
      }
      //  添加完成后显示空白状态页
      if (activeName === '6') {
        if (!this.addGoodsStatus) return false
        else {
          this.addGoodsStatus = false
          // 添加商品完成跳转商品列表
          setTimeout(() => {
            this.$router.push('goods')
          }, 3000)
        }
      }
    },
    //  点击tags标签页时触发
    async tabsClick(tag) {
      console.log(tag)
      // 当触发商品参数
      if (this.activeIndex === '1') {
        const {
          data
        } = await this.$http.get(
          `categories/${this.selectGoodsCate[2]}/attributes`,
          { params: { sel: 'many' } }
        )
        if (data.meta.status !== 200) {
          return this.$message.error('商品参数（动态参数）获取失败')
        }
        //  this.$message.success('商品参数（动态参数）获取成功')
        console.log('商品参数（动态参数）获取成功')
        console.log(data)
        data.data.forEach(item => {
          item.attr_vals = item.attr_vals ? item.attr_vals.split(',') : []
        })

        this.goodsParamsMany = data.data
        console.log(this.goodsParamsMany)
      }
      // 当触发商品属性
      if (this.activeIndex === '2') {
        const {
          data
        } = await this.$http.get(
          `categories/${this.selectGoodsCate[2]}/attributes`,
          { params: { sel: 'only' } }
        )
        if (data.meta.status !== 200) {
          return this.$message.error('商品参数（静态参数）获取失败')
        }
        //  this.$message.success('商品参数（静态参数）获取成功')
        console.log('商品参数（静态参数）获取成功')
        console.log(data)
        this.goodsParamsOnly = data.data
        console.log(this.goodsParamsOnly)
      }
      // 当触发商品图片
      if (this.activeIndex === '3') {
        console.log('商品图片')
      }
      // 完成
      if (this.activeIndex === '6') {
        console.log('完成后')
      }
    },
    // 删除文件时触发
    handleRemove(file) {
      const deletePath = file.response.data.tmp_path
      const index = this.addGoodform.pics.findIndex(
        item => item.pic === deletePath
      )
      this.addGoodform.pics.splice(index, 1)
      console.log(this.addGoodform.pics)
    },
    // 点击上传文件时触发
    handlePreview(file) {
      this.reviewdialog = true
      this.reviewPicPath = file.response.data.url
    },
    // 图片上传完成
    uploadSuccess(response) {
      const picInfo = { pic: response.data.tmp_path }
      this.addGoodform.pics.push(picInfo)
      console.log(this.addGoodform.pics)
    },
    // 提交添加商品
    async subAddGoods() {
      this.$refs.addGoodFormRef.validate(async valid => {
        if (!valid) {
          this.$message({ message: '请将添加商品参数填写完整', type: 'error' })
          return false
        }
        this.goodsParamsMany.forEach(item => {
          const attr = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(',')
          }
          this.addGoodform.attrs.push(attr)
        })
        this.goodsParamsOnly.forEach(item => {
          const attr = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals
          }
          this.addGoodform.attrs.push(attr)
        })
        this.addGoodform.goods_cat = this.selectGoodsCate.join(',')
        this.addGoodform.goods_price = parseInt(this.addGoodform.goods_price)
        this.addGoodform.goods_weight = parseInt(this.addGoodform.goods_weight)
        this.addGoodform.goods_number = parseInt(this.addGoodform.goods_number)
        console.log(this.addGoodform)
        const { data } = await this.$http.post('goods', this.addGoodform)
        console.log(data)
        if (data.meta.status !== 201) {
          this.addGoodsStatus = false
          return this.$message({ message: '添加商品失败', type: 'error' })
        } else {
          this.$message({ message: '添加商品成功', type: 'success' })
          this.activeIndex = '6'
          this.addGoodsStatus = true
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
.el-checkbox {
  margin: 10px;
}
.reviewPic {
  width: 100%;
  height: 100%;
}
.quill-editor {
  margin: 20px auto;
  width: 95%;
  height: 200%;
}
.el-form-item {
  margin: 10px 0;
}
#successBox {
  background-color: #e4e7ed;
  width: 90%;
  padding: 50px;
  margin: 20px auto;
  text-align: center;
  size: 20px;
}
</style>
